'''
Created on 2010/04/02

@author: enu
'''
from oauth.request import Request
from oauth.exceptions import OAuthException
from oauth.credentials import TemporaryTokenCredentials,\
  AuthorizedTokenCredentials

class ServiceProvider(object):

  def requestTemporaryTokenCredentials(self, wsgiRequest, wsgiResponse):
    try:
      request = Request.generateFromWsgiRequest(wsgiRequest)
      request.authenticateRequest()
      temporaryToken = TemporaryTokenCredentials()
      temporaryToken.confirmCallbackURL(request)
      temporaryToken.save()
      temporaryToken.respondTokenCredentials(wsgiResponse)
    except OAuthException, e:
      wsgiResponse.error(e.statusCode)
      wsgiResponse.out.write(e.message)
  
  def authorizeAcess(self, wsgiRequest, wsgiResponse, user):
    try:
      request = Request.generateFromWsgiRequest(wsgiRequest)
      temporaryToken = TemporaryTokenCredentials.load(request)
      temporaryToken.generateVerificationCode()
      temporaryToken.save()
      temporaryToken.callback(wsgiResponse)
    except OAuthException, e:
      wsgiResponse.error(e.statusCode)
      wsgiResponse.out.write(e.message)

  def issueAuthorizedTokenCredentials(self, wsgiRequest, wsgiResponse):
    try:
      request = Request.generateFromWsgiRequest(wsgiRequest)
      request.authenticateRequest()
      temporaryToken = TemporaryTokenCredentials.load(request)
      temporaryToken.confirmVerificationCode(request)
      authorizedToken = AuthorizedTokenCredentials.exchange(temporaryToken)
      authorizedToken.respondTokenCredentials(wsgiResponse)
    except OAuthException, e:
      wsgiResponse.error(e.statusCode)
      wsgiResponse.out.write(e.message)
